package net.caixiaomi.info.ui.matching;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;

import com.alibaba.fastjson.JSONObject;
import com.baidu.mobstat.StatService;

import net.caixiaomi.info.R;
import net.caixiaomi.info.adapter.LotteryAdapter;
import net.caixiaomi.info.app.CommonApp;
import net.caixiaomi.info.base.BaseFragment;
import net.caixiaomi.info.base.progressbar.CircularProgressBar;
import net.caixiaomi.info.base.quickadapter.BaseQuickAdapter;
import net.caixiaomi.info.interfaces.MatchingNumsCallBack;
import net.caixiaomi.info.model.BaseCallModel;
import net.caixiaomi.info.model.LotteryItem;
import net.caixiaomi.info.model.MatchCollectEntity;
import net.caixiaomi.info.model.MatchResultNewModel;
import net.caixiaomi.info.model.MatchingItem;
import net.caixiaomi.info.net.RequestService;
import net.caixiaomi.info.net.ResponseCallback;
import net.caixiaomi.info.net.ResponseError;
import net.caixiaomi.info.net.RetrofitManage;
import net.caixiaomi.info.ui.football.detail.MatchDetailActivity;
import net.caixiaomi.info.ui.main.LotteryFragment;
import net.caixiaomi.info.ui.main.MatchFragment;
import net.caixiaomi.info.util.Constants;
import net.caixiaomi.info.widgets.DefLoading;
import net.caixiaomi.smartrefresh.layout.SmartRefreshLayout;
import net.caixiaomi.smartrefresh.layout.api.RefreshLayout;
import net.caixiaomi.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import retrofit2.Call;

import static android.R.id.list;

/**
 * Created by suntian on 2018/7/20.
 */

public class MatchItemFragment extends BaseFragment implements BaseQuickAdapter.OnItemClickListener, OnRefreshListener {

    @BindView(list)
    RecyclerView mListView;
    @BindView(R.id.progress)
    CircularProgressBar mProgress;
    @BindView(R.id.refresh)
    SmartRefreshLayout mRefresh;
    private MatchItemAdapter mAdapter;

    private String mCurrentTime;
    private String mLeagueId;
    private String mType;

    private boolean interValLoadData=false;  //数据刷新定时器的开关
    private Disposable loadDataTimerDis;
    private int interValTime=60*1000;


    public static MatchItemFragment newInstance() {
        return new MatchItemFragment();
    }


    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        onRefresh();
    }

    @Override
    protected int fragmentLayout() {
        return R.layout.match_item_ftag_layout;
    }

    @Override
    protected void onFragmentCreated(View view, @Nullable Bundle savedInstanceState) {
//        mLoading = new DefLoading(getActivity());
        mRefresh.setOnRefreshListener(this);
        mListView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mAdapter = new MatchItemAdapter(null, new MatchItemAdapter.CollcetCallBack() {
            @Override
            public void collectClick(MatchingItem matchItem) {
                if(TextUtils.equals(matchItem.getIsCollect(),"0")) { //未收藏
                    addCollectMatch(matchItem);
                }else{
                    cancleCollectMatch(matchItem);
                }
            }
        });
        mAdapter.setOnItemClickListener(this);
        mListView.setAdapter(mAdapter);

    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        boolean dealVersion = CommonApp.STORE.getBoolean(Constants.KEY_DEAL_VERSION, false);
        if(!dealVersion){
            return;
        }
        MatchingItem matchItem = mAdapter.getData().get(position);
        if (TextUtils.isEmpty(matchItem.getMatchId())){
        return;
        }
        Intent intent = new Intent(getActivity(), MatchDetailActivity.class);
        intent.putExtra("data", matchItem.getMatchId());
        startActivity(intent);

    }

    public void onRefresh() {
        loadData();
    }

    public void setRequestData(String currentTime,String leagueId,String type,boolean toTop){
        mCurrentTime=currentTime;
        mLeagueId=leagueId;
        mType=type;
        loadData();
        if(toTop){
            mListView.scrollToPosition(0);
        }
    }

    public void setType(String type){
        mType=type;
    }

    private void addCollectMatch(MatchingItem matchItem){
        JSONObject params = new JSONObject();
        params.put("dateStr", mCurrentTime);
        params.put("matchId", matchItem.getMatchId());
        RequestService requestService = RetrofitManage.getInstance().getRequestService();
        Call<BaseCallModel<MatchCollectEntity>> addMatchCollect = requestService.addMatchCollect(params);
        addMatchCollect.enqueue(new ResponseCallback<BaseCallModel<MatchCollectEntity>>(getActivity()) {
            @Override
            public void onSuccess(BaseCallModel<MatchCollectEntity> data) {
                mRefresh.finishRefresh();
                mProgress.setVisibility(View.GONE);
                loadData();
            }

            @Override
            public void onFail(ResponseError error) {
                mProgress.setVisibility(View.GONE);
                mRefresh.finishRefresh();
                dismissLoading();
            }

            @Override
            public void onError() {
                mProgress.setVisibility(View.GONE);
                mRefresh.finishRefresh();
                dismissLoading();
            }
        });
    }

    public void cancleCollectMatch(MatchingItem matchItem){
        JSONObject params = new JSONObject();
        params.put("dateStr", mCurrentTime);
        params.put("matchId", matchItem.getMatchId());
        RequestService requestService = RetrofitManage.getInstance().getRequestService();
        Call<BaseCallModel<MatchCollectEntity>> addMatchCollect = requestService.cancleMatchCollect(params);
        addMatchCollect.enqueue(new ResponseCallback<BaseCallModel<MatchCollectEntity>>(getActivity()) {
            @Override
            public void onSuccess(BaseCallModel<MatchCollectEntity> data) {
                mRefresh.finishRefresh();
                mProgress.setVisibility(View.GONE);
                loadData();
            }

            @Override
            public void onFail(ResponseError error) {
                mProgress.setVisibility(View.GONE);
                mRefresh.finishRefresh();
                dismissLoading();
            }

            @Override
            public void onError() {
                mProgress.setVisibility(View.GONE);
                mRefresh.finishRefresh();
                dismissLoading();
            }
        });
    }

    private void loadData() {
        JSONObject params = new JSONObject();
        params.put("dateStr", mCurrentTime);
        params.put("leagueIds", mLeagueId);
        params.put("type", mType);
        RequestService requestService = RetrofitManage.getInstance().getRequestService();
        Call<BaseCallModel<MatchResultNewModel>> baseCallModelCall = requestService.queryMatchResultNew(params);
        baseCallModelCall.enqueue(new ResponseCallback<BaseCallModel<MatchResultNewModel>>(getActivity()) {
            @Override
            public void onSuccess(BaseCallModel<MatchResultNewModel> data) {
                mRefresh.finishRefresh();
                mProgress.setVisibility(View.GONE);
                MatchResultNewModel modle = data.data;

                List<MatchingItem> lists=modle.getLotteryMatchDTOList();

                if (lists != null&&lists.size()>0) {
                    MatchingItem headerItem = new MatchingItem();
                    headerItem.setMatchDateStr(modle.getMatchDateStr());
                    int finishCount = 0;
                    if (!lists.isEmpty()) {
                        Iterator<MatchingItem> iterator = lists.iterator();
                        while (iterator.hasNext()) {
                            MatchingItem next = iterator.next();
                            if (TextUtils.equals(next.getMatchFinish(), "1")) {
                                finishCount++;
                            }
                        }
                    }
                    headerItem.setType(Constants.ITEM_VIEW_HEADER);
                    lists.add(0, headerItem);
                    mAdapter.setNewData(lists);
                }else{
                    lists=new ArrayList<>();
                    MatchingItem noItem = new MatchingItem();
                    noItem.setType(Constants.ITEM_VIEW_EMPTY);
                    lists.add(0, noItem);
                    mAdapter.setNewData(lists);
                }

                dismissLoading();
            }

            @Override
            public void onFail(ResponseError error) {
                mProgress.setVisibility(View.GONE);
                mRefresh.finishRefresh();
                dismissLoading();
            }

            @Override
            public void onError() {
                mProgress.setVisibility(View.GONE);
                mRefresh.finishRefresh();
                dismissLoading();
            }
        });
    }

    private MatchFragment mParent;
    public void setParent(MatchFragment ff){
        mParent=ff;
    }

    @Override
    public void onResume() {
        super.onResume();
        StatService.onPageStart(getActivity(),"kaijaing-view");

           boolean onresume= getUserVisibleHint();
           boolean parentOnresume=mParent.mOnresume;
           if(onresume&&parentOnresume){
               if(!TextUtils.equals(mType,"2")){
                   loadData();
               }
               if(TextUtils.equals(mType,"0")){
               startTimerTask();
           }
        }

    }

    @Override
    public void onPause() {
        super.onPause();
        StatService.onPageEnd(getActivity(),"kaijaing-view");
        if(TextUtils.equals(mType,"0")){
            cancelTimerTask();
        }

    }

    public void startTimerTask(){

        if(interValLoadData){
            return;
        }
        interValLoadData=true;
        setInterValLoadData(interValTime, new IRxNext() {
            @Override
            public void doNext(long number) {
                loadData();
            }
        });
    }

    private void setInterValLoadData(long milliseconds,final IRxNext next){
        Observable.interval(milliseconds, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable disposable) {
                        loadDataTimerDis=disposable;
                    }

                    @Override
                    public void onNext(@NonNull Long number) {
                        if(next!=null){
                            next.doNext(number);
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    public interface IRxNext{
        void doNext(long number);
    }

    public void cancelTimerTask(){
        if(loadDataTimerDis!=null&&!loadDataTimerDis.isDisposed()){
            loadDataTimerDis.dispose();
//            LogUtil.e("====定时器取消======");
        }
        interValLoadData=false;
    }

}
